package de.koller.reason.render.pipeline;

import de.koller.oceanFramework.math.IProjection;
import de.koller.reason.math.IsometricProjection;
import de.koller.oceanFramework.plain.util.RRaster;
import de.koller.reason.render.obj.IRenderObject;
import de.koller.reason.render.obj.Polygon;
import java.util.Arrays;

public class RenderPipeline {

	private final IProjection projection;
	
	private final RRaster raster;
	private final float[][] depthBuffer;
	
	private final Rasterizer rasterizer = new Rasterizer( this );
	
	public RenderPipeline( RRaster raster, IProjection projection ) {
		this.raster = raster;
		this.depthBuffer = new float[ raster.width ][ raster.height ];
		this.projection = projection;
	}
	
	public void preRenderStep() {
		for( int i = 0; i < depthBuffer.length; i++ )
			Arrays.fill( depthBuffer[i], Float.MIN_VALUE );
		raster.clear( 0xff000000 );
	}
	
	public void renderObj( IRenderObject obj ) {
		for( IRenderObject.RenderEntity e : obj.getRenderEntities() )
			renderEntity( e );
	}
	
	public void renderEntity( IRenderObject.RenderEntity e ) {
		for( Polygon p : e.polygons )
			renderPolygon( p );
	}
	
	public void renderPolygon( Polygon p ) {
		rasterizer.rasterPolygon( p, projection );
	}
	
	public void finishRenderStep() {
		
	}
	
	public void writeFragment( Fragment f ) {
		renderFragment( f );
	}
	
	private void renderFragment( Fragment f ) {
		if( f.x < 0 || f.x >= raster.width || f.y < 0 || f.y >= raster.height )
			return;
		if( depthBuffer[f.x][f.y] != Float.MIN_VALUE && depthBuffer[f.x][f.y] >= f.depth )
			return;
		
		raster.setPixel( f.color, f.x, f.y );
		depthBuffer[f.x][f.y] = f.depth;
	}

}
